package com.xingxue.entity;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

@SuppressWarnings("serial")
@Data
@Slf4j
public class User implements Serializable, UserDetails {

	private int id;

	private String username;

	@JsonIgnore
	private String password;

	private List<Role> roles = new ArrayList<>();
	
	private Integer orgId;

	private Integer[] orgIds;

	@JsonIgnore
	public Set<Module> getAvailableModules() {
		Set<Module> available = new HashSet<>();
		for (Role role : this.roles) {
			available.addAll(role.getModules());
		}
		return available;
	}

	/**
	 * 检查是否包含改父模块
	 * 
	 * @param parentModule
	 *            父模块对象
	 * @return
	 */
	public boolean containsParentModule(Module parentModule) {
		for (Module m : getAvailableModules()) {
			if (m.getPid() == parentModule.getId()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 检查是否包含该模块,根据id检查
	 * 
	 * @param module
	 *            模块对象
	 * @return
	 */
	public boolean containsModule(Module module) {
		for (Module m : getAvailableModules()) {
			if (m.getId() == module.getId()) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 检查是否包含该模块,根据code检查
	 * <br>
	 * 以开头匹配即可
	 * @param url
	 * @return
	 */
	public boolean containsUrl(String url) {
		StringBuilder sb = new StringBuilder(128);
		sb.append("当前用户的权限有：");
		for (Module m : getAvailableModules()) {
			sb.append("["+m.getCode()+"]");
		}
		log.debug(sb.toString());
		for (Module m : getAvailableModules()) {
			if (url.startsWith(m.getCode())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return this.roles.stream().map(r->new SimpleGrantedAuthority("ROLE_"+r.getName())).collect(Collectors.toList());
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}
